package cn.com.rocketmq.transaction;

import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * 事务消息生产者
 * @author xuhaixiang
 * @date 2023-09-11
 */
public class Producer {

    /**
     * 日志对象
     */
    private static  final Logger logger = LoggerFactory.getLogger(Producer.class);

    public static void main(String[] args) {
        TransactionMQProducer producer = null;
        try {
            producer = new TransactionMQProducer("transactionProductor");
            producer.setNamesrvAddr("192.168.113.101:9876");
            //开启异步线程，用于异步执行本地事务执行和回查两个动作
            ExecutorService service = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS ,new ArrayBlockingQueue<>(20000), new ThreadFactory(){
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("transaction");
                    return thread;
                }
            });
            producer.setExecutorService(service);

            //设置本地事务执行器
            producer.setTransactionListener(new TransactionListenerImpl());
            producer.start();
            String[] tags = {"tagA", "tagB", "tagC", "tagD", "tagE"};
            for (int i = 0; i < 10; i++) {
                for (String tag : tags) {
                    Message message = new Message("rocketmq_transactionDemo", tag, (tag + " Hello world!" + i).getBytes("UTF-8"));
                    TransactionSendResult result = producer.sendMessageInTransaction(message, null);
                    logger.info("消息发送成功！消息ID={}" + result.getMsgId());
                }
            }
            //让生产者存活一段时间可以回调本地事务执行和本地事务回查
            Thread.sleep(60000);
        } catch (Exception e) {
            logger.error("消息发送异常！", e);
        } finally {
            if (producer != null) {
                producer.shutdown();
            }
        }
    }
}
